package org.WhyMCA.Services;

/**
@author Danilo '' Riso >> danilo DOT riso AT gmail DOT com
* @author Androidiani Dev Team
* @version 1.0
*/

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import org.WhyMCA.Adapters.WhyMCAAdapter;
import org.WhyMCA.Models.WhyMCANewsModel;
import org.WhyMCA.NetManager.NetworkMgr;
import org.WhyMCA.NetManager.NetworkMgr.requestCallback;
import org.WhyMCA.Utils.DialogMgr;
import org.WhyMCA.Utils.Global;
import org.WhyMCA.Utils.PreferencesMgr;
import org.WhyMCA.Utils.XMLParser;
import org.WhyMCA.Utils.DialogMgr.DialogCallback;
import org.WhyMCA.WhyMCANews.R;
import org.WhyMCA.WhyMCANews.WhyMCANews;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

public class WhyMCAService extends Service implements requestCallback {
		
	private NetworkMgr _netmgr;
	private ArrayList<WhyMCANewsModel> _nlwhymcaloc, _nlwhymcanet;
	private ProgressDialog _pd;
	private TimerTask scanTask;
	private SharedPreferences.Editor _prefed;
	private SharedPreferences _sharpref;
	private static long _timemill;
	private NotificationManager mNotificationManager;
	private final IBinder mBinder = new LocalBinder();
	private static OnServiceListener _sl;
	private static Intent _imain;
	private static boolean _winfocus;
	private String _ilxmlnet, _ilxmlloc, _lastlocdate, _lastnetdate;
		
	public interface OnServiceListener {
    	
		public void onDataReceived();
	
	}
	
	public class LocalBinder extends Binder {
		WhyMCAService getService() {
            return WhyMCAService.this;
        }
    }
	
	@Override
	public IBinder onBind(Intent intent) {
		
		return mBinder;
		
	}
	
	@Override
	public void onCreate() {
		
		Global.setCtx(this);
		createElements();
		
	}

	@Override
	public void onDestroy() {
		
		if(scanTask!=null){
	 	      scanTask.cancel();
	 	   }
		
		_netmgr.stopConn();
				
	}
			
	@Override
	public void onStart(Intent intent, int startid) {
	
    	final Handler handler = new Handler();
    	Timer t = new Timer();
    	
    	scanTask = new TimerTask() {
            public void run() {
            	 handler.post(new Runnable() {
                     public void run() {
                    	executeRequest();
                    	 //Toast.makeText(Global.getCtx(), "Update", Toast.LENGTH_SHORT).show();
                     }
            	 });
            }
        };

        System.out.println(getTimeMill());
        t.schedule(scanTask, 0, getTimeMill());
          		
	}
	
	public static void setCallBack(final OnServiceListener servicelistener) {
		
		_sl = servicelistener;
		
	}
	
	private void executeRequest() {
    	
    	_netmgr.resetBuff();
		_netmgr.setCallBack(this);
		_netmgr.doRequest();
					    	
    }
	
	public void onPause(){

 	   if(scanTask!=null){
 	      scanTask.cancel();
 	   }
 	 
	}
	
	public static void setTimeMill(long timemill) {
    	
    	_timemill = timemill;
    	
    }
    
    private static long getTimeMill() {
    	
    	return _timemill;
    	
    }
		
    public static void setMainIntent(Intent intent) {
    	
    	_imain = intent;
    	
    }
    
    private Intent getMainIntent() {
    	
    	return _imain;
    	
    }
    
    public static void setWindowsFocus(boolean b) {
    	
    	_winfocus = b;
    	
    }
    
    private boolean getWindowsFocus() {
    	
    	return _winfocus;
    	
    }
    
    @Override
	public void onRequestStart() {

		Global.getCtx();
		//_pd = ProgressDialog.show(Global.getCtx(), Global.getCtx().getText(R.string.update_progress_dialog_title), Global.getCtx().getText(R.string.update_progress_dialog_text), true, false);
				
	}

	@Override
	public void onRequestStop(boolean result) {
				
		System.out.println("Risultato: " + result);
		
		if(!result) {
					
			_ilxmlnet = _netmgr.getBuff();
						
			if(PreferencesMgr.checkXmlCurrent()) {
	    		
	    		_ilxmlloc = PreferencesMgr.getXmlCurrent();
	    			    		
	    		if(isUpdated(_ilxmlloc, _ilxmlnet)) {
	    			
	    			PreferencesMgr.setXmlCurrent(_ilxmlnet);
	    			whymcaNotification(_nlwhymcanet.get(0).getTitle());
	    			WhyMCANews.setModelObject(_nlwhymcanet);
	    			_sl.onDataReceived();
	    			
	    		}
	    		    		    		
	    	} else {
	    		
	    		PreferencesMgr.setXmlCurrent(_ilxmlnet);
	    		
	    	}
						
		} else {
			
			Global.getCtx();
			//DialogMgr.dialogConnError(this);
			
		}
		
		//_pd.cancel();
									
	}
        
	public void createElements() {
    	
		String ns = Global.getCtx().NOTIFICATION_SERVICE;
		mNotificationManager = (NotificationManager) getSystemService(ns);
    	_netmgr = new NetworkMgr();
        	
    	_sharpref = Global.getCtx().getSharedPreferences("WhyMCA", 0);
    	_prefed = _sharpref.edit();
    	    	                
        PreferencesMgr.createElements();
        
        WhyMCAService.setTimeMill(_sharpref.getLong("TIME", 30000));
                    
	}
	
	/*
 	*Invia l'XML contenente le news al parsatore
 	*/
    private boolean isUpdated(String _ilxmlloc, String _ilxmlnet) {
	
    	try {
		
    		_nlwhymcaloc = XMLParser.getNews(_ilxmlloc);
    		_nlwhymcanet = XMLParser.getNews(_ilxmlnet);
    		_lastlocdate = _nlwhymcaloc.get(0).getDataTrunk();
    		_lastnetdate = _nlwhymcanet.get(0).getDataTrunk();
    		
    		// Et voila
    		//Log.d("Status", Integer.toString(_news.size()));
    		//this._nadapter = new WhyMCAAdapter(this, _nlwhymca);
    		//_newslist.setAdapter(this._nadapter);
    	    		
    		//_llocality.setOnItemClickListener(this);
    		//setListAdapter(this._wdapter);
    		//getListView().setAdapter(this._wdapter);
    		    	  	    		
		
    	} catch (XmlPullParserException e) {
		
    		// Manca la gestione degli errori!!!
    		//TODO Auto-generated catch block
    		e.printStackTrace();
    	
    	} catch (IOException e) {
		
    		// MAnca la gestione degli errori!!!
    		//TODO Auto-generated catch block
        	e.printStackTrace();
        	
    	} catch (IndexOutOfBoundsException e) {
		
    		// MAnca la gestione degli errori!!!
    		//TODO Auto-generated catch block
        	e.printStackTrace();
        	
    	}
	
    	if(_lastlocdate.equals(_lastnetdate))
			
			return false;
		
		else
		    			
			return true;
    	
    }
	
	private void whymcaNotification(String title) {
		
		int icon = R.drawable.icon;
		CharSequence tickerText = "WhyMCA";
		long when = System.currentTimeMillis();
		
		Notification notification = new Notification(icon, tickerText, when);
		
		if(PreferencesMgr.getSoundConfig()) {
			
			notification.sound = Uri.parse("android.resource://org.WhyMCA.WhyMCANews/" + R.raw.whymca);
			
		}
				 
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		
		Context context = getApplicationContext();
		CharSequence contentTitle = "WhyMCA News";
		CharSequence contentText = ("Aggiornamento: " + title);
		
		if(!getWindowsFocus()) {
			
			Intent notificationIntent = getMainIntent();
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
			
			notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
			mNotificationManager.notify(1, notification);
			
		}
					
	}
		
}
